package mustry.alone.service.impl;

import org.apache.commons.codec.binary.Base64;

import mustry.alone.service.SignService;
import mustry.alone.utils.sign.RSA;

public class RsaServiceImpl implements SignService {
	
	private static final String charset = "UTF-8";

	public String encrypt(String text, String privateKey) {
		try {
			byte[] bytes = RSA.encryptByPrivateKey(text.getBytes(charset), privateKey);
			return Base64.encodeBase64String(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String decrypt(String text, String publicKey) {
		try {
//			byte[] bytes = RSA.decryptByPrivateKey(Base64.decodeBase64(text.getBytes(charset)), publicKey);
			byte[] bytes = RSA.decryptByPublicKey(Base64.decodeBase64(text.getBytes(charset)), publicKey);
			return new String(bytes,charset);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String sign(String text, String privateKey, String charset) {
		String sign = "";
		try {
			sign = RSA.sign(text, privateKey, charset);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sign;
	}

	public boolean verify(String text, String sign, String publicKey,String charset) {
		try {
			return RSA.verify(text, sign, publicKey, charset);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
